package com.tz.fruit.controller;

import com.tz.fruit.entity.User;
import com.tz.fruit.service.IUserService;
import com.tz.fruit.validation.Group1;
import com.tz.fruit.validation.Group2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/18.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/index")
    public String index(){

       return "index";

    }

    /**
     * 跳转到关于我们页面
     */
    @RequestMapping("/about")
    public String about(){
        return "about";
    }
    /**
     * 跳转到联系我们页面
     */
    @RequestMapping("/contact")
    public String contact(){
        return "contact";

    }

    @RequestMapping("/registerView")
    public String registerView() {
        return "user/register";
    }

    @RequestMapping("/register")
    public String register(Model model,User u, HttpServletResponse resp,  String username, String flag, String password, String email, String tel) throws ServletException, IOException {
        if ("true".equals(flag)) {
            //说明验证成功，注册用户
            User user = new User(username, password, tel, email);
            userService.save(user);
            return "redirect:/product/index";
        } else {
            //说明只是验证用户名是否存在
            //获取文档输出流
            PrintWriter out = resp.getWriter();
            User user = userService.findByUsername(username);
            //判断用户是否存在
            if (user == null) {
                //此处输出的值,通过ajax中的responseText是可以进行获取到的.
                out.print("1");
            } else {
                out.print("0");
            }
            model.addAttribute("u",u);
            return null;
        }
    }

    //由后台调到登录jsp界面
    @RequestMapping("/loginView")
    public String loginView(){
        return "user/login";
    }

    /**
     * 登录
     */
    @RequestMapping("/logincl")
    public  String logincl(Model model, HttpServletRequest req, HttpServletResponse resp, String username, String password, String flag)throws ServletException, IOException {

        //4.根据username来获取User对象.
        User user = userService.findByUsername(username);

        //5.判断user对象是否存在.
        if (null != user) {


            //获取user的登录权限
            int rank=user.getRank();

            //继续判断password是否正确.
            if (user.getPassword().equals(password)) {
                req.getSession().setAttribute("user", user);
                if(rank==1){
                    return "backstage/index";
                }

                if (flag != null) {
                    //说明勾选了记住密码,如果勾选了,但是该控件没有提供value属性的值,那么默认是on,否则是null
                    //创建Cookie对象

                    //为了防止用户名出现中文,所以需要对用户名进行一级编码
                    String uname = URLEncoder.encode(username, "utf-8");

                    Cookie cookie = new Cookie("username", uname + ":" + password);

                    //设置过期时间为一周,单位是秒
                    cookie.setMaxAge(60 * 60 * 24 * 7);

                    //设置cookie可访问路径[整个应用都有效]
                    cookie.setPath("/");

                    //将cookie写入到客户端
                    resp.addCookie(cookie);
                } else {
                    Cookie[] cookies = req.getCookies();
                    if (null != cookies && cookies.length > 0) {
                        for (Cookie c : cookies) {
                            if ("username".equals(c.getName())) {
                                //Cookie cc = new Cookie("username",null);
                                c.setValue(null);
                                ////设置该cookie的过期时间.
                                c.setMaxAge(1);

                                c.setPath("/");

                                resp.addCookie(c);
                            }
                        }
                    }
                }
                //resp.sendRedirect(req.getContextPath()+"/book/list");
                return "redirect:/product/index";

            } else {
                Map<String, String> list = new HashMap<String, String>();
                list.put("passwordError","密码不正确");
                model.addAttribute("list",list);
                return "user/login";
            }

        } else {

            //说明当前用户不存在.
            //System.out.println("用户名不存在...");

            //重定向到登陆的视图servlet
            //resp.sendRedirect(req.getContextPath()+"/jsp/user/login.jsp?error=0");
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("userError", "用户名不正确");
            model.addAttribute("maps", maps);
            return "user/login";
        }

    }
    /**
     * 安全退出
     */
    @RequestMapping("/safeExit")
    protected String safeExit(HttpServletRequest req) throws ServletException, IOException {
        req.getSession().invalidate();//清空session

        //重定向到登陆界面
        return "index";
    }

    @RequestMapping("/checkpwd")
    public String checkpwd(HttpServletRequest req,String oldpassword){
        User user= (User) req.getSession().getAttribute("user");
        if(oldpassword.equals(user.getPassword())){
            return "1";
        }else{
            return "0";
        }
    }
    @RequestMapping("/changepwd")
    public String changepwd(){
        return "user/password";
    }
    @RequestMapping("updatePwd")
    public String updatePwd(HttpServletRequest req,String password){
        User user= (User) req.getSession().getAttribute("user");
        user.setPassword(password);
        userService.update(user);
        return "index";
    }

}
